<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Finance;

use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\AntNest\UserCenter;
/**
 * 退车商款
 * Class DealerRefund
 *
 * @author Xmh
 */
class DealerRefund
{
    private $DealerRefund;
    private $CarModel;
    private $Addr;

    public function __construct()
    {
        $this->DealerRefund = M('DealerRefund');
        $this->CarModel = new CarModel();
        $this->Addr = new Address();
    }


    /**
     * 获取退车商款的列表
     * @param integer $page
     * @param int $size
     * @param array $params
     * @return multitype:unknown string
     */
    public function get_dealer_refund_list($page = 1, $size = 10, $params){
        $page = (int) $page < 1 ? 1 : (int) $page;
        $size = (int) $size < 1 ? 10 : (int) $size;
        $map = array();
        if($params['status']){
            $map['dr.status'] = ['eq',$params['status']];
        }
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['eq',$params['location_area']];
        }
        if (!empty($params['keywords'])) {
            $keywords = trim($params['keywords']);
            if(is_numeric($params['keywords'])){
                $uc = new UserCenter();
                $info1 = $uc->info_bymobile($params['keywords'],2,1);
                $where['du.uid'] = ['eq',$info1['account_id']];
            }else{
                $where['o.order_no'] = ['LIKE', '%'.$keywords.'%'];
                $where['c.car_no'] = ['LIKE','%'.$keywords.'%'];
                $where['cd.contact_person'] = ['LIKE', '%'.$keywords.'%'];
                $where['_logic'] = 'OR';
            }
            $map['_complex'] = $where;
        }
        if(empty($params['location_area']) && $params['bc_city']){
            $map['c.location_area'] = ['in',$params['bc_city']];
        }
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.last_time,
                 c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,
                 cd.contact_person,du.uid,dr.id,dr.refund_time,dr.createtime";
        $prefix = C('DB_PREFIX');
        $order = 'dr.id DESC,o.order_id DESC';
        $total = $this->DealerRefund->alias('dr')
            ->join($prefix . "order as o ON o.order_id = dr.order_id")
            ->join($prefix . "cars as c ON c.car_id = dr.car_id")
            ->join($prefix . "car_dealer as cd ON cd.dealer_id = dr.dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id = du.dealer_id")
            ->where($map)->count();
        $list =  $this->DealerRefund->alias('dr')->field($cols)
            ->join($prefix . "order as o ON o.order_id = dr.order_id")
            ->join($prefix . "cars as c ON c.car_id = dr.car_id")
            ->join($prefix . "car_dealer as cd ON cd.dealer_id = dr.dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id = du.dealer_id")
            ->where($map)->limit($size)->page($page)->order($order)->select();
//        echo M()->_sql();
        if(!empty($list)){
            $dealer = new Dealer();
            $list= $dealer->get_contact_mobile_byAntNest($list);
        }
        if(!empty($list)){
            foreach($list as $key=>$val){
                $list[$key]['order_no'] = $val['order_no'];
                $list[$key]['location_area_name'] = $this->Addr->get_name_by_code($val['location_area']);
                $brand = $this->CarModel->get_model_by_id($val['brand_id'], 'brand');
                $series = $this->CarModel->get_model_by_id($val['series_id'], 'series');
                $model = $this->CarModel->get_model_by_id($val['model_id']);
                $list[$key]['car_no'] = $val['car_no'];
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
                $list[$key]['createtime'] = date("Y-m-d H:i",strtotime($val['createtime']));
                $list[$key]['refund_time'] = date("Y-m-d H:i",strtotime($val['refund_time']));
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 退车商款详情
     * @param  int $refund_id
     * @return mixed
     */
    public function dealer_refund_detail($refund_id){
        $condition['dr.id'] = ['eq',$refund_id];
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.last_time,
                 c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,
                 c.car_color,c.emission,c.pointer_mileage,c.reg_city,c.first_reg_date,c.composite_state,c.history_state,
                 c.accident_level,c.transfer_limit,c.vin,
                 cd.contact_person,du.uid,
                 di.issue_id,di.issue_type,di.status as issue_status,di.updatetime as issue_done_time,
                 di.emp_id as issue_done_empid,di.cut_down_price,di.remark,
                 dr.id,dr.remark as refund_remark,dr.refund_time,dr.emp_id as refund_emp,dr.refund_amount,
                 dr.status as refund_status,pl.amount,pl.pay_mode,ll.first_pay_money";
        $prefix = C('DB_PREFIX');
        $order = 'o.order_id DESC';
        $res =  $this->DealerRefund->alias('dr')->field($cols)
            ->join($prefix . "order as o ON o.order_id = dr.order_id")
            ->join($prefix . "cars as c ON c.car_id = dr.car_id")
            ->join($prefix . "dealer_issue as di ON di.issue_id = dr.issue_id")
            ->join($prefix . "car_dealer as cd ON cd.dealer_id = dr.dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join($prefix . "proceeds_log as pl ON pl.order_id = dr.order_id")
            ->join(" LEFT JOIN " . $prefix . "loan_log as ll ON ll.order_id = dr.order_id")
            ->where($condition)->order($order)->find();
        if(!empty($res)){
            $dealer = new Dealer();
            $res = $dealer->get_contact_mobile_byAntNestfind($res);
        }
        $brand = $this->CarModel->get_model_by_id($res['brand_id'], 'brand');
        $series = $this->CarModel->get_model_by_id($res['series_id'], 'series');
        $model = $this->CarModel->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = round($res['pointer_mileage'] / 10000, 2);
        $res['location_area_name'] = $this->Addr->get_name_by_code($res['location_area']);
        $res['reg_city'] = $this->Addr->get_name_by_code($res['reg_city']);
        $res['car_plate_number'] = C('PLATE_PREFIX')[$res['plate_prefix']] . $res['plate_suffix'];
        //车商付款金额

        $res['pay_amount'] = '0.00';
        if($res['pay_mode'] == 1){  //线下全款
            $res['pay_amount'] = $res['amount'];
        }elseif($res['pay_mode'] == 2){ //有首付贷款
            $res['pay_amount'] = $res['first_pay_money'];
        }
        //仲裁信息
        if($res['issue_done_empid'] > 0) {
            $employee = \AuctionCore\Account\Back\Employee::user_info_id($res['issue_done_empid']);
            $res['issue_done_emp'] = $employee['real_name'];
            $res['issue_done_mobile'] = $employee['mobile'];
        }
        $res['issue_done_time'] = date("Y年m月d日 H:i",strtotime($res['issue_done_time']));
        //退款信息
        if($res['refund_emp'] > 0){
            $employee = \AuctionCore\Account\Back\Employee::user_info_id($res['refund_emp']);
            $res['refund_emp'] = $employee['real_name'];
        }
        if($res['issue_status'] == 2){ //车商违约扣款
            $res['issue_type_name'] = '扣除';
            $res['refund_type'] = 2;
            $res['formula'] = '（车商付款 - 扣除金额）：';
            $res['refund_amount_total'] = sprintf("%1.2f",$res['pay_amount'] - $res['cut_down_price']);
        }elseif($res['issue_status'] == 3){   //我方违约补偿
            $res['issue_type_name'] = '补偿';
            $res['refund_type'] = 1;
            $res['formula'] = '（车商付款 + 补偿金额）：';
            $res['refund_amount_total'] = sprintf("%1.2f",$res['pay_amount'] + $res['cut_down_price']);
        }
        return $res;
    }

    /**
     * 创建退车商款
     *
     * @param array $data
     */
    public function add_dealer_refund($data = array())
    {
        if(empty($data)){
            return false;
        }
        return $this->DealerRefund->add($data);
    }



    /**
     * 更新退车商款处理
     *
     * @param array $data
     */
    public function save_dealer_refund($data = array()){
        if(empty($data)){
            return false;
        }
        $data['refund_time'] = date("Y-m-d H:i:s",time());
        return $this->DealerRefund->save($data);
    }

    /**
     * 获取退车商款详情
     *
     * @param $id
     * @param $cols
     * @return bool|mixed
     */
    public function get_dealer_refund($id, $cols="*"){
        if($id < 1){
            return false;
        }
        return $this->DealerRefund->field($cols)->find($id);
    }

}
